<?php
/*

  Template Name: Visualization Fuel

 */

get_template_part('secondary', 'header');
get_template_part('secondary', 'sidebar');

$type_id = 3; //combustible

//Logic to save records
$current_user = wp_get_current_user();
$user_id = $current_user->ID;

$year = date('Y');
$month = date('m');

if($month == 1){
    $year = $year - 1;
    $month = 12;
} else {
    $month = $month - 1;
}

$previous_year = $year - 1;

$consumption_gas_query = $wpdb->get_results($wpdb->prepare("select * from bpa_registry_consumption where user_id = %d and type_id = %d and subtype_id = 1 and ((year = %d and month <= %d) or year = %d) order by year desc, month desc limit 12", $user_id, $type_id, $year, $month, $previous_year));
$consumption_gas = array_reverse($consumption_gas_query, true);

$consumption_diesel_query = $wpdb->get_results($wpdb->prepare("select * from bpa_registry_consumption where user_id = %d and type_id = %d and subtype_id = 2 and ((year = %d and month <= %d) or year = %d) order by year desc, month desc limit 12", $user_id, $type_id, $year, $month, $previous_year));
$consumption_diesel = array_reverse($consumption_diesel_query, true);

$consumption_glp_query = $wpdb->get_results($wpdb->prepare("select * from bpa_registry_consumption where user_id = %d and type_id = %d and subtype_id = 3 and ((year = %d and month <= %d) or year = %d) order by year desc, month desc limit 12", $user_id, $type_id, $year, $month, $previous_year));
$consumption_glp = array_reverse($consumption_glp_query, true);

$consumption_gnv_query = $wpdb->get_results($wpdb->prepare("select * from bpa_registry_consumption where user_id = %d and type_id = %d and subtype_id = 4 and ((year = %d and month <= %d) or year = %d) order by year desc, month desc limit 12", $user_id, $type_id, $year, $month, $previous_year));
$consumption_gnv = array_reverse($consumption_gnv_query, true);

$consumption_table = $wpdb->get_results($wpdb->prepare(
        "select c.user_id, c.year, c.month, c.quantity, c.price, st.name
        from bpa_registry_consumption c
        left join bpa_consumption_subtype st
        on c.subtype_id = st.id
        where c.user_id = %d and c.type_id = %d and ((c.year = %d and c.month <= %d) or c.year = %d) 
        order by c.year desc, c.month desc, c.subtype_id asc limit 48", 
        $user_id, $type_id, $year, $month, $previous_year));

$filter = $_REQUEST['filter'];
if(!isset($filter)){
    $filter="qty";
}

?>

<div class="col-sm-9 col-sm-offset-3 col-md-10 col-md-offset-2 main">

    <div id="dash-content" class="visualiza-content">

        <?php if (have_posts()) : ?>

            <?php while (have_posts()) : the_post(); ?>

                <header>
                    <h2><?php the_title(); ?></h2>
                    <h5>&nbsp;</h5>
                </header>
        
                <div class="filter">
                    <form id="filter_form">
                       Ver consumo por: 
                        <select id="filter_select" name="filter">
                            <option value="qty" <?php if($filter=='qty') echo 'selected' ?> >Galones</option>
                            <option value="price" <?php if($filter=='price') echo 'selected' ?>>Soles</option>
                        </select> 
                    </form>
                </div>

                <div class="v-canvas">
                    <div class="canvas-area">
                        <canvas id="detailed_fuel_chart" height="500"></canvas>
                    </div>
                    <div id="legend" width="766" height="100"></div>
                    <p class="nota-combustible">NOTA: En este gráfico se han convertido los consumo de GLP en litros y GNV en metros cúbicos a galones</p>
                </div>

                <div class="visualiza">

                    <div class="v-left">
                        <h3><?php the_title(); ?></h3>
                        <p><?php the_content(); ?></p>
                        <a class="buton agregar" href="<?php echo Helpers::get_user_register_url(); ?>">Agregar nuevo consumo</a>
                    </div>

                    <div class="v-right">

                        <table>
                            <thead>
                                <tr>
                                    <th>Mes</th>
                                    <th>Tipo</th>
                                    <th>Cantidad</th>
                                    <th>Soles</th>
                                </tr>
                            </thead>
                            <tbody>
                                <?php 
                                    $total_consumption=0;
                                    $total_price=0;
                                    foreach ($consumption_table as $registry) { ?>
                                        <tr>
                                            <td ><?php echo get_year_from_index($registry->month) . "<br>" . $registry->year; ?></td>
                                            <td><?php echo $registry->name; ?></td>
                                            <td class="v-precio"><?php echo $registry->quantity; ?> <strong><?php if ($registry->name === "GNV" ) {
                                                     echo " m<sup>3</sup>";
                                                }elseif($registry->name === "GLP") {
                                                    echo " l";
                                                }elseif($registry->name === "Gasolina" or $registry->name === "Diesel" ) {
                                                    echo " Gal";
                                                }?>
                                            </strong> 
                                            </td>
                                            <td class="v-precio">S/.<?php echo sprintf("%.2f", $registry->price); ?></td>
                                        </tr> 
                                <?php   $total_consumption += $registry->quantity;
                                        $total_price += $registry->price;
                                    } ?>
                                <tr>
                                    <th>Total</th>
                                    <th>&nbsp;</th>
                                    <th class="v-precio"><?php echo $total_consumption; ?> Gl</th>
                                    <th class="v-precio">S/. <?php echo sprintf("%.2f", $total_price); ?></th>
                                </tr>
                            </tbody>
                        </table>

                    </div>

                </div>

            <?php endwhile; ?>

        <?php endif; ?>

    </div>

</div>

<?php

$gas_data = array(0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0);
$diesel_data = array(0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0);
$glp_data = array(0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0);
$gnv_data = array(0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0);

$i = 0;
foreach ($consumption_gas as $registry) {
    $item_data = $filter=="qty" ? $registry->quantity : $registry->price;
    $gas_data[$i] = sprintf("%.2f", $gas_data[$i] + $item_data);
    $i++;
}

$i = 0;
foreach ($consumption_diesel as $registry) {
    $item_data = $filter=="qty" ? $registry->quantity : $registry->price;
    $diesel_data[$i] = sprintf("%.2f", $diesel_data[$i] + $item_data);
    $i++;
}

$i = 0;
foreach ($consumption_glp as $registry) {
    
    $qty = $registry->quantity;
    $qty = 0.264172051 * $qty;                         
    
    $item_data = $filter=="qty" ? $qty : $registry->price;
    $glp_data[$i] = sprintf("%.2f", $glp_data[$i] + $item_data);
    $i++;
}

$i = 0;
foreach ($consumption_gnv as $registry) {
    
    $qty = $registry->quantity;
    $qty = 1.056688204 * $qty;                               
    
    $item_data = $filter=="qty" ? $qty : $registry->price;
    $gnv_data[$i] = sprintf("%.2f", $gnv_data[$i] + $item_data);
    $i++;
}

//labels of axis x
$labels = get_graph_label_months($consumption_gas);

$unit_label = '';
if($filter=="qty"){
    $unit_label = '<%= value %> Gal';
}else{
    $unit_label = 'S/. <%= value %>';
}

?>

<script>

    var fuel_ctx = document.getElementById("detailed_fuel_chart").getContext("2d");

    var fuel_data = {
        labels: ['',<?php echo "'".implode($labels, "','")."'"; ?>],
        datasets: [
            {
                label: "Gasolina",
                fillColor: "rgba(220,220,220,0.2)",
                strokeColor: "rgba(220,220,220,1)",
                pointColor: "#fff",
                pointStrokeColor: "#fff",
                lineColor: "#fff",
                pointHighlightFill: "#fff",
                pointHighlightStroke: "rgba(220,220,220,1)",
                data: [0, <?php echo implode($gas_data, ","); ?>]
            },
            {
                label: "Diesel",
                fillColor: "rgba(220,220,220,0.2)",
                strokeColor: "rgba(220,220,220,1)",
                pointColor: "#0f0",
                pointStrokeColor: "#0f0",
                lineColor: "#0f0",
                pointHighlightFill: "#0f0",
                pointHighlightStroke: "rgba(220,220,220,1)",
                data: [0, <?php echo implode($diesel_data, ","); ?>]
            },
            {
                label: "GLP",
                fillColor: "rgba(220,220,220,0.2)",
                strokeColor: "rgba(220,220,220,1)",
                pointColor: "#000",
                pointStrokeColor: "#000",
                lineColor: "#000",
                pointHighlightFill: "#000",
                pointHighlightStroke: "rgba(220,220,220,1)",
                data: [0, <?php echo implode($glp_data, ","); ?>]
            },
            {
                label: "GNV",
                fillColor: "rgba(220,220,220,0.2)",
                strokeColor: "rgba(220,220,220,1)",
                pointColor: "#00f",
                pointStrokeColor: "#00f",
                lineColor: "#00f",
                pointHighlightFill: "#00f",
                pointHighlightStroke: "rgba(220,220,220,1)",
                data: [0, <?php echo implode($gnv_data, ","); ?>]
            },
        ]
    };

    var options = {
        scaleShowGridLines : true,
        scaleFontColor: "rgba(0,0,0,.05)",
        scaleFontColor: "rgba(255,255,255,1)",
        scaleGridLineWidth : 1,
        bezierCurve : false,
        scaleLabel : "<?php echo $unit_label; ?>",
        bezierCurveTension : 0.4,
        pointDot : true,
        pointDotRadius : 5,
        pointDotStrokeWidth : 2,
        pointHitDetectionRadius : 20,
        datasetStroke : true,
        datasetStrokeWidth : 2,
        responsive: true,
        maintainAspectRatio: false,
        multiTooltipTemplate: "<?php echo $unit_label; ?>",
        datasetFill : true,
        legendTemplate : "<ul class=\"<%=name.toLowerCase()%>-legend\"><% for (var i=0; i<datasets.length; i++){%><li><span style=\"background-color:<%=datasets[i].pointColor%>\"></span><%if(datasets[i].label){%><%=datasets[i].label%><%}%></li><%}%></ul>"
    };

    var myLineChart = new Chart(fuel_ctx).Line(fuel_data, options);
    jQuery("#legend").html(myLineChart.generateLegend());

</script>

<?php get_template_part('secondary', 'footer'); ?>